<?php

/**
 *   OPENSHOP 管理中心套装商品管理
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: group_promotion.php,v 1.0 2009/06/19 09:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require_once(dirname(__FILE__).'/includes/init.php');

require_once(ROOT_PATH . '/admin/includes/lib_goods.php');

$exc = new exchange($os->table('group_promotion'),$db,'group_promotion_id','group_name');

/* act操作项的初始化 */
if (empty($_REQUEST['act'])){
    $_REQUEST['act'] = 'list';
}else{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}
if($_REQUEST['act']=='list'){
	
	//检查权限
	admin_priv();
		
	$smarty->assign('ur_here',      '套装商品管理');   
	$smarty->assign('action_link',  array('href' => 'group_promotion.php?act=add', 'text' => '添加商品套装'));
	
    $ongoing = empty($_REQUEST['ongoing']) ? '' : $_REQUEST['ongoing'] ;    
	$group_pro_list = get_group_pro_list($ongoing);
	
	$smarty->assign('group_pro_list',   $group_pro_list['promotion']);
    $smarty->assign('filter',       $group_pro_list['filter']);
    $smarty->assign('record_count', $group_pro_list['record_count']);
    $smarty->assign('page_count',   $group_pro_list['page_count']);		

	$smarty->assign('full_page',    1);
	
    assign_query_info();
	
	$smarty->display('group_promotion_list.tpl');
	
}elseif($_REQUEST['act']=='add' || $_REQUEST['act']=='edit'){
	
    $is_add = $_REQUEST['act'] == 'add';
    
    $priv_str = $is_add ? 'add_group' : 'edit_group';
    admin_priv($priv_str);
        
    $smarty->assign('form_act', $is_add ? 'insert' : 'update');
    
    /* 初始化、取得优惠活动信息 */
    if ($is_add)
    {
        $group_pro = array(
            'group_promotion_id'        => 0,
            'group_code'      => '',
            'group_name'      => '',
            'description'     => '',
            'price_type'      => 1,
            'price_type_ext'  => '',
            'start_time'    => local_date('Y-m-d H:i'),
            'end_time'      => local_date('Y-m-d H:i', strtotime('+1 week')),
            'user_rank'     => ''
        );
    }
    else
    {
        if (empty($_GET['group_pro_id']))
        {
            sys_msg('invalid param');
        }
        $group_pro_id = intval($_GET['group_pro_id']);
        $group_pro = group_pro_info($group_pro_id);
        if (empty($group_pro))
        {
            sys_msg('您要操作的商品套装不存在');
        }
        
        $sql = "SELECT * FROM " . $os->table('group_promotion_gallery') . " WHERE group_promotion_id = '$group_pro[group_promotion_id]'";
        
        $img_list = $db->getAll($sql);

        /* 格式化相册图片路径 */
        if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 0))
        {
            foreach ($img_list as $key => $gallery_img)
            {
                $gallery_img[$key]['img_url'] = $_CFG['pre_fetch_img']. $gallery_img['img_original'];
                $gallery_img[$key]['thumb_url'] =  $_CFG['pre_fetch_img']. $gallery_img['img_original'];
            }
        }
        else
        {
            foreach ($img_list as $key => $gallery_img)
            {
                $gallery_img[$key]['thumb_url'] =  $_CFG['pre_fetch_img']. $gallery_img['img_url'];
            }
        }
        $smarty->assign('img_list', $img_list);
    }
    $smarty->assign('group_pro', $group_pro);
    
	/* 取得用户等级 */
    $user_rank_list = array();
    $sql = "SELECT rank_id, rank_name FROM " . $os->table('user_rank');
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $row['checked'] = strpos(',' . $group_pro['user_rank'] . ',', ',' . $row['rank_id']. ',') !== false;
        $user_rank_list[] = $row;
    }
    $smarty->assign('user_rank_list', $user_rank_list);
    
    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加商品套装管理');
    }
    else
    {
        $smarty->assign('ur_here', '编辑商品套装记录');
    }
    $href = 'group_promotion.php?act=list';
    if (!$is_add)
    {
        $href .= '&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '商品套装管理'));
        
	assign_query_info();
	
	$smarty->display('group_promotion_info.tpl');
	
}elseif($_REQUEST['act']=='insert' || $_REQUEST['act'] == 'update'){  
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';
        
    $priv_str = $is_add ? 'add_group' : 'edit_group';
    admin_priv($priv_str);
    
    /* 检查名称是否重复 */
    $group_name = sub_str($_POST['group_name'], 50, false);
    if (!$exc->is_only('group_name', $group_name,intval($_POST['group_promotion_id'])))
    {
       sys_msg(sprintf("商品套装名称 %s 已经存在！", stripslashes($group_name)), 1);
    }
    
    /* 检查代码是否重复 */
    if (!$exc->is_only('group_code', $_POST['group_code'],intval($_POST['group_promotion_id'])))
    {
       sys_msg(sprintf("商品套装代码 %s 已经存在！", stripslashes($_POST['group_code'])), 1);
    }
    
    /* 检查享受优惠的客户等级 */
    if (!isset($_POST['user_rank']))
    {
        sys_msg('请设置享受优惠的客户等级');
    }    

    /*  设置计价类型，取得计价类型的数值 */
    if(intval($_POST['price_type']) == 1){
       $_POST['price'] = $_POST['price_type_ext'];
       $_POST['discount'] = 0;
    }elseif(intval($_POST['price_type']) == 2){
       $_POST['discount'] = $_POST['price_type_ext'];
       $_POST['price'] = '0.00';
    }
    /* 提交值 */
    $group_pro = array(
        'group_promotion_id'        => intval($_POST['group_promotion_id']),
        'group_code'    => $_POST['group_code'],
        'group_name'    => $group_name,
        'description'   => $_POST['description'],
        'price_type'    => $_POST['price_type'],
        'price'         => $_POST['price'],
        'discount'      => $_POST['discount'],
        'start_time'    => local_strtotime($_POST['start_time']),
        'end_time'      => local_strtotime($_POST['end_time']),
        'user_rank'     => isset($_POST['user_rank']) ? join(',', $_POST['user_rank']) : '0',
        'add_time'		=> time()
    );
    /* 保存数据 */
    if ($is_add)
    {
        $db->autoExecute($os->table('group_promotion'), $group_pro, 'INSERT');
        $group_pro['group_promotion_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('group_promotion'), $group_pro, 'UPDATE', "group_promotion_id = '$group_pro[group_promotion_id]'");
    }  
    /* 处理商品套装相册图片 */
	handle_group_pro_gallery_image($group_pro['group_promotion_id'], $_FILES['img_url'], $_POST['img_desc']);    
     /* 记日志 */
    if ($is_add){
        admin_log($group_pro['group_name'], 'add', 'group_promotion');
    }else{
        admin_log($group_pro['group_name'], 'edit', 'group_promotion');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add){
        $links = array(
            array('href' => 'group_promotion.php?act=add', 'text' => '继续添加商品套装'),
            array('href' => 'group_promotion.php?act=list', 'text' => '返回商品套装列表')
        );
        sys_msg('添加商品套装成功', 0, $links);
    }else{
        $links = array(
            array('href' => 'group_promotion.php?act=list&' . list_link_postfix(), 'text' => '返回商品套装列表')
        );
        sys_msg('编辑商品套装成功', 0, $links);
    }     
}elseif ($_REQUEST['act']=='remove'){
	
	/* 检查权限 */
    check_authz_json('drop_group');

    $group_pro_id = intval($_GET['id']);
    $group_pro = group_pro_info($group_pro_id);
    if (empty($group_pro))
    {
        make_json_error('您要操作的商品套装不存在');
    }
    $gpg_t_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('group_promotion_goods_type'). " WHERE group_promotion_id='$group_pro_id'");
    $gp_g_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('group_promotion_gallery'). " WHERE group_promotion_id='$group_pro_id'");
    $gpg_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('group_promotion_goods'). " WHERE group_promotion_id='$group_pro_id'");
    if($gpg_t_count==0 && $gp_g_count==0 && $gpg_count==0){
	    /* 删除该颜色 */
	    if($exc->drop($group_pro_id)){
		    /* 记日志 */
		    admin_log($group_pro['group_name'], 'remove', 'group_promotion');   	
	    }
    }else{
    	make_json_error('"'.$group_pro['group_name'] .'" 该商品套装与商品套装类型、商品、套装商品相册还有关联,您不能删除!');
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'group_promotion.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;	
}elseif($_REQUEST['act']=='query'){
    $list = get_group_pro_list($ongoing);

    $smarty->assign('group_pro_list',  $list['promotion']);
    $smarty->assign('filter',          $list['filter']);
    $smarty->assign('record_count',    $list['record_count']);
    $smarty->assign('page_count',      $list['page_count']);
    
    make_json_result($smarty->fetch('group_promotion_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));	
}/*------------------------------------------------------ */
//-- 删除图片
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_image')
{
    check_authz_json('drop_group_image');

    $img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);

    /* 删除图片文件 */
    $sql = "SELECT img_id, img_original FROM " . $GLOBALS['os']->table('group_promotion_gallery') .
            " WHERE img_id = '$img_id'";
    $id = $GLOBALS['db']->getOne($sql);
  
    if($filesync->sync_type=='ftp'){
	    $filesync->connect();
	    @$filesync->drop($img_id, 'group_pro_gallery');
	    $filesync->quit();	    		
	}else{ 
        if (!empty($row['img_original']))
        {
            @unlink(SOURCE_PATH . $row['img_original']);
        }		
	}
	
    /* 删除数据 */
    $sql = "DELETE FROM " . $GLOBALS['os']->table('group_promotion_gallery') . " WHERE img_id = '$img_id' LIMIT 1";
    $GLOBALS['db']->query($sql);

    clear_cache_files();
    make_json_result($img_id);
}

function group_pro_info($group_pro_id){
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('group_promotion') .
            " WHERE group_promotion_id = '$group_pro_id'";
    $row = $GLOBALS['db']->getRow($sql);
    if (!empty($row))
    {
        $row['start_time'] = local_date('Y-m-d H:i', $row['start_time']);;
        $row['end_time'] = local_date('Y-m-d H:i', $row['end_time']);
        if($row['price_type']==1){
           $row['price_type_ext'] = $row['price'];
        }elseif($row['price_type']==2){
           $row['price_type_ext'] = $row['discount'];     	
        }
        unset($row['price'],$row['discount'],$row['add_time']);   
    }

    return $row;	
}

function get_group_pro_list($ongoing){
    $result = get_filter();
    if ($result === false){
        /* 分页大小 */
        $filter = array();
        $where = 'WHERE 1 ';
        if($ongoing == 1){
           $now = gmtime();
           $where .= " AND start_time <= '$now' AND end_time >= '$now' ";
        }
        
        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['os']->table('group_promotion').' '.$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        
        /* 查询记录 */
		$sql = "SELECT * FROM ". $GLOBALS['os']->table('group_promotion').' '.$where. 
		       " ORDER BY group_promotion_id DESC LIMIT ".
		        $filter['start'] .", $filter[page_size]";
        set_filter($filter, $sql);
    }else{
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['start_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['start_time']);
        $row['end_time']   = local_date($GLOBALS['_CFG']['time_format'], $row['end_time']);

        $list[] = $row;
    }
    
    return array('promotion' => $list, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function handle_group_pro_gallery_image($group_pro_id, $image_files, $image_descs){
    /* 是否处理缩略图 */
    $proc_thumb = (isset($GLOBALS['shop_id']) && $GLOBALS['shop_id'] > 0)? false : true;
    foreach ($image_descs AS $key => $img_desc){
        /* 是否成功上传 */
        $flag = false;
        if (isset($image_files['error']))
        {
            if ($image_files['error'][$key] == 0)
            {
                $flag = true;
            }
        }
        else
        {
            if ($image_files['tmp_name'][$key] != 'none')
            {
                $flag = true;
            }
        }
        if ($flag)
        {
            // 生成缩略图
//            if ($proc_thumb)
//            {
//                $thumb_url = $GLOBALS['image']->make_thumb($image_files['tmp_name'][$key], $GLOBALS['_CFG']['thumb_width'],  $GLOBALS['_CFG']['thumb_height']);
//                $thumb_url = is_string($thumb_url) ? $thumb_url : '';
//            }

            $upload = array(
                'name' => $image_files['name'][$key],
                'type' => $image_files['type'][$key],
                'tmp_name' => $image_files['tmp_name'][$key],
                'size' => $image_files['size'][$key],
            );
            if (isset($image_files['error']))
            {
                $upload['error'] = $image_files['error'][$key];
            }
            
		    if($GLOBALS['filesync']->sync_type=='ftp'){
	            $GLOBALS['filesync']->connect();
	            $GLOBALS['filesync']->setting('group_pro_gallery', 'data/group_pro_gallery');
		        $gallery_affix_data   = $GLOBALS['filesync']->put_up($upload); // 原始图片
	            $img_original   = $gallery_affix_data['virtual_path'];
	            $GLOBALS['filesync']->quit();
		    }else{
            	$img_original = $GLOBALS['filesync']->upload_image($upload, 'group_pro_gallery');		    	
		    }  
            if ($img_original === false || empty($img_original))
            {
                sys_msg('相册上传错误', 1, array(), false);
            }	       
	        
            $img_url = $img_original;

            $thumb_url = $img_original;
                
            // 如果服务器支持GD 则添加水印
//            if ($proc_thumb && gd_version() > 0)
//            {
//                $pos        = strpos(basename($img_original), '.');
//                $newname    = dirname($img_original) . '/' . $GLOBALS['image']->random_filename() . substr(basename($img_original), $pos);
//                copy('../' . $img_original, '../' . $newname);
//                $img_url    = $newname;
//
//                $GLOBALS['image']->add_watermark('../'.$img_url,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']);
//            }

            /* 重新格式化图片名称 */
//            $img_original = reformat_image_name('group_pro_gallery', $group_pro_id, $img_original, 'source');
//            $img_url = reformat_image_name('group_pro_gallery', $group_pro_id, $img_url, 'group_pro');
//            $thumb_url = reformat_image_name('group_pro_thumb', $group_pro_id, $thumb_url, 'thumb');
            $sql = "INSERT INTO " . $GLOBALS['os']->table('group_promotion_gallery') . " (group_promotion_id, img_url, img_desc, thumb_url, img_original, is_reveal) " .
                    "VALUES ('$group_pro_id', '$img_url', '$img_desc', '$thumb_url', '$img_original', 1)";            
            $GLOBALS['db']->query($sql);
        }
    }
}
?>